﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using YanShu.Entity;

namespace YanShu.Utils
{
    //  构建数据加码
    class ProxyMessageEncoder : MessageToByteEncoder<ProxyMessage>
    {

        public static int TYPE_SIZE = 1;

        public static int SERIAL_NUMBER_SIZE = 8;

        public static int URI_LENGTH_SIZE = 1;


        //编码操作
        protected override void Encode(IChannelHandlerContext context, ProxyMessage message, IByteBuffer output)
        {

            int bodyLength = TYPE_SIZE + SERIAL_NUMBER_SIZE + URI_LENGTH_SIZE;

            byte[] uriBytes = null;

            if (message.GetUri() != null)
            {
                uriBytes = Encoding.UTF8.GetBytes(message.GetUri());
                bodyLength += uriBytes.Length;
            }

            if (message.GetData() != null)
            {
                bodyLength += message.GetData().Length;
            }

            // write the total packet length but without length field's length.
            output.WriteInt(bodyLength);

            output.WriteByte(message.GetType());
            output.WriteLong(message.GetSerialNumber());

            if (uriBytes != null)
            {
                output.WriteByte((byte)uriBytes.Length);
                output.WriteBytes(uriBytes);
            }
            else
            {
                output.WriteByte((byte)0x00);
            }

            if (message.GetData() != null)
            {
                output.WriteBytes(message.GetData());
            }

        }
    }
}
